using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using ShoppingCenter.Backend.Api.Db;
using ShoppingCenter.Backend.Api.Model;
using ShoppingCenter.Backend.Api.Params;
using ShoppingCenter.Backend.Api.Repository;
using ShoppingCenter.Backend.Api.Utils;

namespace ShoppingCenter.Backend.Api.Controllers
{
    // [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class UsersController : ControllerBase
    {
        private IConfiguration _configuration;
        //初始化token
        private TokenParameter _toKenParameter;

        private IRepository<User> _usersRepository;
        private IRepository<Admin> _adminRepository;

        public UsersController(IConfiguration configuration, IRepository<User> usersRepository, IRepository<Admin> adminRepository)
        {
            _configuration = configuration;
            _usersRepository = usersRepository;
            _adminRepository = adminRepository;
            _toKenParameter = _configuration
                   .GetSection("TokenParameter")
                   .Get<TokenParameter>();
        }


        //登录获取token
        [AllowAnonymous]
        [HttpPost, Route("token")]
        public dynamic GetToken(CURUser newUser)
        {
            var username = newUser.Name.Trim();
            var password = newUser.Password.Trim();

            var user =
                _usersRepository
                    .Table
                    .Where(x => x.Name == username && x.Password == password)
                    .FirstOrDefault();


            if (user == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "用户名或密码不正确，请确认后重试"
                };
            }

            var token = ToKenHelper.GenerateToekn(_toKenParameter, user.Name);
            var refreshToken = "112358";

            return new
            {
                Code = 1000,
                Data = new { Token = token, refreshToken = refreshToken ,user},
                Msg = "用户登录成功^_^"
            };
        }


        //获取所有用户
        public dynamic Get()
        {

            var currentPage = int.Parse(Request.Query["currentPage"][0]);
            var pageSize = int.Parse(Request.Query["pageSize"][0]);

            // 分页
            var users = _usersRepository.Table.ToList().OrderBy(x => x.Id);
            var user=users.Skip((currentPage - 1) * pageSize).Take(pageSize);;

            return new
            {
                Code = 1000,
                Data = new
                {
                    Data = users,
                    Pager = new { currentPage, pageSize, totalSize = users.Count() }
                },
                Msg = "获取所有用户成功"
            };
        }

        //添加
        [HttpPost]
        public dynamic Post(CURUser newUser)
        {
            var username = newUser.Name.Trim();
            var password = newUser.Password.Trim();


            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {

                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "账号或密码不能为空"
                };
            }

            var u = _usersRepository.Table.Where(x => x.Name == username).ToList().FirstOrDefault();
            var admin = _adminRepository.Table.Where(x => x.Name == username).ToList().FirstOrDefault();

            //判断当前用户名是否已经注册
            if (u != null || admin != null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "当前用户名已存在,请换个用户名后重试"
                };
            }


            var user = new User
            {
                Name = username,
                Password = password,
                Remarks = newUser.Remarks,
            };

            //将账号密码插入到Users表中
            _usersRepository.Insert(user);


            return new
            {
                Code = 1000,
                Data = user,
                Msg = "创建用户成功"
            };

            //将结果实例化后输出

        }

        //根据id修改用户信息
        [HttpPut("{id}")]
        public dynamic Put(int id, CURUser updateUser)
        {
            var username = updateUser.Name.Trim();
            var password = updateUser.Password.Trim();


            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "账号或密码不能为空"
                };
            }


            //通过Id获取要修改的用户
            var user = _usersRepository.GetById(id);

            if (user == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "你要更新的用户不存在"
                };
            }

            var u = _usersRepository.Table.Where(x => x.Name == username).ToList().FirstOrDefault();
            var admin = _adminRepository.Table.Where(x => x.Name == username).ToList().FirstOrDefault();

            if (admin != null || (u != null && u.Id != id))
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "当前用户名已存在,请换个用户名后重试"
                };
            }

            //将要修改的账号密码重新赋给user
            user.Name = username;
            user.Password = password;
            user.Remarks = updateUser.Remarks;

            _usersRepository.Update(user);

            return new
            {
                Code = 1000,
                Data = user,
                Msg = "更新数据成功"
            };

            // return JsonHelper.Serialize(res);

        }

        //根据id删除用户
        [HttpDelete("{id}")]
        public dynamic Dalete(int id)
        {

            var user = _usersRepository.GetById(id);

            if (user == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = string.Format("无法删除id为{0}的用户", id)
                };
            }

            _usersRepository.Delete(id);

            return new
            {
                Code = 1000,
                Data = "",
                Msg = "删除用户成功"
            };
        }


    }
}